package club.jdiy.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Arrays;

/**
 * Cookie操作工具类.
 * @author ziquee(子秋) QQ号:39886616 主页: http://www.jdiy.club
 * @version 20200517
 */
@SuppressWarnings("ALL")
public final class CookieUtils {
    private CookieUtils(){}
    /**
     * 获取cookie
     *
     * @param name cookie名称
     * @return cookie值，取不到返回空字符串(永远不会返回null)
     */
    public static String getCookie(HttpServletRequest request, String name) {
        String rtn = null;
        javax.servlet.http.Cookie[] c = request.getCookies();
        if (c != null) {
            for (Cookie aC : c) {
                if (aC.getName().equals(name)) {
                    try {
                        rtn = aC.getValue() == null ? null : URLDecoder.decode(aC.getValue(), "utf-8");
                    } catch (UnsupportedEncodingException ignored) {
                    }
                    break;
                }
            }
        }
        return rtn == null ? "" : rtn;
    }

    /**
     * 创建或删除cookie.  通过此方法设置的cookie，将在浏览器关闭时过期。<br />
     *
     * @param name  要创建或删除的会话级变量名称。<br />
     * @param value 设置cookie的值,如果此值为null,将删除cookie
     *              如果value的值等于null(即删除)时, 那么name可以是由逗号分隔的多个变量名,例如：<br />
     *              cookie("companyId, companyRole, companyUid", null);　这样程序将会同时删除companyId, companyRole, companyUid三个cookie.
     */
    public static void setCookie(HttpServletRequest request, HttpServletResponse response, String name, String value) {
        setCookie(request, response, name, value, -1);
    }

    /**
     * 创建或删除cookie.  所设置的cookie将在指定的时间expiry(以秒为单位)后过期.<br />
     *               如果value的值等于null(即删除)时, 那么name可以是由逗号分隔的多个变量名,例如：<br />
     *               cookie("companyId, companyRole, companyUid", null);　这样程序将会同时删除companyId, companyRole, companyUid三个cookie.
     *
     * @param name   要创建或删除的会话级变量名称。<br />
     * @param value  设置cookie的值,如果此值为null,将删除cookie
     * @param expiry 以秒为单位的cookie过期时间.若值为负，将在浏览器关闭时过期
     */
    public static void setCookie(HttpServletRequest request, HttpServletResponse response, String name, String value, int expiry) {
        if (value != null) {//create mode
            try {
                javax.servlet.http.Cookie c = new javax.servlet.http.Cookie(name, java.net.URLEncoder.encode(value, "utf-8"));
                c.setMaxAge(expiry);
                c.setPath(request.getContextPath() + "/");
                response.addCookie(c);
            } catch (UnsupportedEncodingException ignore) {
            }
        } else {//delete mode
            javax.servlet.http.Cookie[] c = request.getCookies();
            if (c == null) return;
            Arrays.stream(c).filter(aC -> name.contains(aC.getName())).forEach(aC -> {
                aC.setValue(null);
                aC.setMaxAge(0);
                aC.setPath(request.getContextPath() + "/");
                response.addCookie(aC);
            });
        }
    }
}